#pragma once
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include "Log.hpp"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "arpa/inet.h"
#include "InetAddr.hpp"
using namespace LogModule;
const int defaultfd = -1;
using func_t = std::function<void(int sockfd, const std::string&, InetAddr&)>;
class UdpServer {
public:
    UdpServer(uint16_t port, func_t func)
    :_sockfd(defaultfd),
    _port(port),
    _isrunning(false),
    _func(func) {}
    void Start() {
        _isrunning = true;
        // 接收数据
        while(_isrunning) {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if(s > 0) { // 拿到数据了
                InetAddr client(peer);
                buffer[s] = '\0';
                _func(_sockfd, buffer, client);
                // LOG(LogLevel::INFO) << "[" << ip << " : " << port << "]# " << buffer; // 打印消息内容
                // sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr*)&peer, len); // 返回处理结果
            }
        }
    }
    void Init() {
        // 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0) {
            LOG(LogLevel::FATAL) << "socket error";
        }else {
            LOG(LogLevel::INFO) << "socket success, sockfd : " << _sockfd;
        }
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // 使用任意ip
        // 绑定
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0) {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }else {
            LOG(LogLevel::INFO) << "bind success, sockfd : " << _sockfd;
        }
    }
    ~UdpServer() {}
private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};